package com.example.cadmin.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.cadmin.entity.Archives;
import com.example.cadmin.entity.ElectronArchives;
import com.example.cadmin.mapper.ArchivesMapper;
import com.example.cadmin.mapper.ElectronArchivesMapper;
import com.example.cadmin.utils.ResponseModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 电子档案 服务实现类
 * </p>
 *
 * @author zzsoft
 * @since 2024-04-29
 */
@Service
public class ElectronArchivesService extends ServiceImpl<ElectronArchivesMapper, ElectronArchives> {

    @Resource
    public ElectronArchivesMapper electronArchivesMapper;
    @Resource
    public ArchivesMapper archivesMapper;

    /**
     * pdf合并列表
     */
    public Map<String, Object> pdfList(String archivesId, int limit, int page) {
        //参数一是当前页，参数二是每页个数
        IPage<Map<String, Object>> electronPage = new Page<>(page, limit);
        QueryWrapper<ElectronArchives> wrapper = new QueryWrapper<>();
        //判断一下是否有搜索条件
        if (StrUtil.isNotEmpty(archivesId)) {
            wrapper.like("archives_id", archivesId);

        }
        electronPage = electronArchivesMapper.selectMapsPage(electronPage, wrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "数据请求成功");
        map.put("count", electronPage.getTotal());
        map.put("data", electronPage.getRecords());
        return map;
    }

    /**
     * 删除档案
     */
    public ResponseModel deleteElectron(String id) {
        ElectronArchives electronArchives = electronArchivesMapper.selectById(Convert.toInt(id));

        String[] strings = id.split(",");
        List<String> idList = CollUtil.newArrayList(strings);
        int delCount = electronArchivesMapper.deleteBatchIds(idList);
        if (delCount > 0) {
            List<ElectronArchives> electronArchivesList = electronArchivesMapper.selectList(new QueryWrapper<ElectronArchives>()
                    .eq("archives_id", electronArchives.getArchivesId()));
            if (electronArchivesList.size() == 0) {
                archivesMapper.update(null, new UpdateWrapper<Archives>()
                        .eq("id", electronArchives.getArchivesId()).set("electron_file", 0));
                return ResponseModel.success("close","删除成功");
            }
            return ResponseModel.success("删除成功");
        } else {
            return ResponseModel.fail("删除失败,请重新尝试");
        }

    }

}
